package com.shangye.http;

import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HttpServletResponse {
    private Socket socket;

    private int statusCode = 200;
    private String statusReson = "OK";
    private File contentFile;


    private Map<String,String> headers = new HashMap<>();
    public HttpServletResponse(Socket socket){
        this.socket = socket;
    }

    public void response()throws IOException{

        sendStatusLine();
        sendHeaders();
        sendContent();

    }
    private void sendStatusLine() throws IOException{

        println("HTTP/1.1" + " " + statusCode + " " +statusReson);
    }
    private void sendHeaders()throws IOException{
        Set<Map.Entry<String, String>> entries = headers.entrySet();
        for (Map.Entry<String, String> entry : entries){
            println(entry.getKey()+":"+entry.getValue());
        }
        println("");

    }
    private void sendContent()throws IOException{
        if (contentFile!=null){
            try (
                    InputStream fis = new FileInputStream(contentFile);
            ){
                OutputStream out = socket.getOutputStream();
                byte[] data = new byte[1024*10];
                int len;
                while ((len = fis.read(data))!=-1){
                    out.write(data,0,len);
                }
            }
        }
    }

    private void println(String line) throws IOException {
        OutputStream out = socket.getOutputStream();
        out.write(line.getBytes(StandardCharsets.ISO_8859_1));
        out.write(13);
        out.write(10);
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getStatusReson() {
        return statusReson;
    }

    public void setStatusReson(String statusReson) {
        this.statusReson = statusReson;
    }

    public File getContentFile() {
        return contentFile;
    }

    public void setContentFile(File contentFile) {
        this.contentFile = contentFile;
        addHeaders("Content-Type" , new MimetypesFileTypeMap().getContentType(contentFile));
        addHeaders("Content-Length" ,contentFile.length()+"");
    }

    public Map<String, String> getHeaders() {
        return headers;
    }


    public void addHeaders(String key,String value){
        headers.put(key,value);
    }

}
